/**
 * Author: Andrew Shore
 * Date Last Modified: April 19,2009
 * CSCE 146: Homework 07, PQ.java
 * 
 * Description:
 * This class implements a priority queue of Process Records using
 * an Array List. The Process Records are sorted by priority queue with the
 * Record with the highest priority at the beginning of the Array List and
 * the element with the lowest priority at the end of the Array List. Process
 * Records can be added to the queue and the highest priority element can be
 * removed.
 */
import java.util.ArrayList;
import java.util.Scanner;


public class PQ implements IPQ {
	String classLabel = "PQ:";
	private int size;
	private ArrayList<ProcessRecord> list;
	
	/**
	 * Default Constructor
	 */
	public PQ(){	
		size = 0;
		this.list = new ArrayList<ProcessRecord>();
		
	}
	
	/**
	 * Accessors
	 */
	public ArrayList<ProcessRecord> getList() {
		return list;
	}
	
	public int getSize() {
		return list.size();
	}
	
	/**
	 * Mutators
	 */
	public void setList(ArrayList<ProcessRecord> list) {
		this.list = list;
	}
		
	/**
	 * Adds record to the end of the ArrayList and calls the sort method
	 * 
	 * Parameters: newRecord - record being added
	 */
	public void insert(ProcessRecord newRecord) {
		this.list.add(newRecord);
		
		//sorts the array starting at the record that was just added
		this.sort();
	}
	
	/**
	 * Insertion sort method, called when each item is added to the end 
	 * of the list and puts that item in the appropriate place
	 */
	public void sort(){
		int counter = list.size() - 1;
		
		
		for(int i = 0; i < list.size() - 1; i++){
			if(list.get(counter).getPriority() > list.get(counter - 1).getPriority()){
				ProcessRecord element = list.get(counter);
				list.set(counter, list.get(counter - 1));
				list.set(counter - 1, element);
				counter--;
			}
			else{
				return;
			}
		}//for(int i = 0; i < list.size() - 1; i++)
	}
	
	/**
	 * Returns the element at the first index of the ArrayList, which is the
	 * element with the highest priority
	 */
	public ProcessRecord max() {
		return list.get(0);
	}

	/**
	 * Removes the max element(element at index 0) shifts all elements one element
	 * to the left and returns the element
	 */
	public ProcessRecord remove() {
		
		ProcessRecord max = list.get(0);
		
		for(int i = 0; i < list.size() - 1; i++){
			list.set(i, list.get(i + 1));
		}//for(int i = 0; i < list.size() - 1; i++)
		
	
		list.remove(list.size() - 1);
		
		return max;
	}
	
	/**
	 * Returns a String of the ArrayList
	 */
	public String toString(){
		 String s = "";

		    if(0 == this.getSize())
		    {
		      s = String.format("%nFile is empty.");
		    }
		    else
		    {
		      for(int i = 0; i < this.getSize(); i++)
		      {
		        s += String.format("%nsubscript %d %s",
		                           i, list.get(i).toString());
		      }
		    }

		    return s;
	}





}